package com.ruoyi.web.controller.api;

import java.util.List;
import java.util.HashMap;
import java.util.Map;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.math.BigDecimal;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.estate.FeeBill;
import com.ruoyi.system.service.estate.IFeeBillService;

/**
 * 费用管理API Controller
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/api/fee")
public class FeeApiController extends BaseController
{
    @Autowired
    private IFeeBillService feeBillService;

    /**
     * 查询当前用户的费用账单列表
     */
    @Anonymous
    @GetMapping("/list")
    public TableDataInfo list()
    {
        try {
            // 获取当前登录用户ID
            Long userId = SecurityUtils.getUserId();
            
            // 设置分页信息
            startPage();
            
            // 查询用户关联的费用账单
            FeeBill feeBill = new FeeBill();
            feeBill.setResidentId(userId);
            List<FeeBill> list = feeBillService.selectFeeBillList(feeBill);
            
            return getDataTable(list);
        } catch (Exception e) {
            e.printStackTrace();
            return new TableDataInfo();
        }
    }

    /**
     * 获取费用账单详情
     */
    @Anonymous
    @GetMapping("/{billId}")
    public AjaxResult getInfo(@PathVariable("billId") Long billId)
    {
        try {
            // 获取当前登录用户ID
            Long userId = SecurityUtils.getUserId();
            
            // 查询费用账单信息
            FeeBill feeBill = feeBillService.selectFeeBillById(billId);
            
            // 验证账单是否属于当前用户
            if (feeBill != null && feeBill.getResidentId() != null && feeBill.getResidentId().equals(userId)) {
                return AjaxResult.success(feeBill);
            } else {
                return AjaxResult.error("无权访问该账单信息");
            }
        } catch (Exception e) {
            return AjaxResult.error("获取账单详情失败：" + e.getMessage());
        }
    }

    /**
     * 缴费
     */
    @Anonymous
    @PostMapping("/pay")
    public AjaxResult pay(@RequestBody Map<String, Object> params)
    {
        try {
            // 获取当前登录用户ID
            Long userId = SecurityUtils.getUserId();
            
            // 获取账单ID列表
            List<?> billIdList = (List<?>) params.get("billIds");
            
            if (billIdList == null || billIdList.isEmpty()) {
                return AjaxResult.error("请选择要缴费的账单");
            }
            
            // 验证账单是否属于当前用户并更新状态
            for (Object billIdObj : billIdList) {
                // 将Integer转换为Long
                Long billId = Long.valueOf(billIdObj.toString());
                FeeBill feeBill = feeBillService.selectFeeBillById(billId);
                
                if (feeBill == null || !feeBill.getResidentId().equals(userId)) {
                    return AjaxResult.error("无权操作账单ID：" + billId);
                }
                
                // 更新账单状态为已缴费
                feeBill.setBillStatus("1"); // 已缴费
                feeBill.setPaymentTime(new Date()); // 设置缴费时间
                feeBill.setPaymentMethod("2"); // 设置缴费方式为微信支付
                feeBill.setUpdateBy(SecurityUtils.getUsername());
                
                feeBillService.updateFeeBill(feeBill);
            }
            
            return AjaxResult.success("缴费成功");
        } catch (Exception e) {
            return AjaxResult.error("缴费失败：" + e.getMessage());
        }
    }

    /**
     * 获取费用统计
     */
    @Anonymous
    @GetMapping("/statistics")
    public AjaxResult getStatistics()
    {
        try {
            // 获取当前登录用户ID
            Long userId = SecurityUtils.getUserId();
            
            // 查询用户关联的费用账单
            FeeBill feeBill = new FeeBill();
            feeBill.setResidentId(userId);
            List<FeeBill> allBills = feeBillService.selectFeeBillList(feeBill);
            
            // 计算统计数据
            BigDecimal unpaidAmount = BigDecimal.ZERO;
            BigDecimal monthlyPaid = BigDecimal.ZERO;
            BigDecimal yearlyTotal = BigDecimal.ZERO;
            
            // 获取当前年月
            SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy");
            SimpleDateFormat monthFormat = new SimpleDateFormat("yyyy-MM");
            String currentYear = yearFormat.format(new Date());
            String currentMonth = monthFormat.format(new Date());
            
            for (FeeBill bill : allBills) {
                BigDecimal amount = bill.getAmount();
                
                // 待缴费用
                if ("0".equals(bill.getBillStatus()) || "3".equals(bill.getBillStatus())) {
                    unpaidAmount = unpaidAmount.add(amount);
                }
                
                // 本月已缴
                if ("1".equals(bill.getBillStatus()) && bill.getPaymentTime() != null) {
                    String payMonth = monthFormat.format(bill.getPaymentTime());
                    if (currentMonth.equals(payMonth)) {
                        monthlyPaid = monthlyPaid.add(amount);
                    }
                }
                
                // 年度累计
                if ("1".equals(bill.getBillStatus()) && bill.getPaymentTime() != null) {
                    String payYear = yearFormat.format(bill.getPaymentTime());
                    if (currentYear.equals(payYear)) {
                        yearlyTotal = yearlyTotal.add(amount);
                    }
                }
            }
            
            Map<String, String> statistics = new HashMap<>();
            statistics.put("unpaidAmount", unpaidAmount.toString());
            statistics.put("monthlyPaid", monthlyPaid.toString());
            statistics.put("yearlyTotal", yearlyTotal.toString());
            
            return AjaxResult.success(statistics);
        } catch (Exception e) {
            return AjaxResult.error("获取费用统计失败：" + e.getMessage());
        }
    }
} 